//
//  MLURL.m
//  Pods
//
//  Created by molon on 15/7/1.
//
//

#import "MLURL.h"
#import "MLKitDefine.h"

@interface MLURL()

@property (nonatomic, assign) NSSearchPathDirectory searchPathDirectory;
@property (nonatomic, assign) NSSearchPathDomainMask searchPathDomainMask;
@property (nonatomic, assign) BOOL isForSearchPath;

@end

@implementation MLURL

+ (MLURL*)fileURLWithPath:(NSString *)path isDirectory:(BOOL)isDir searchPathDirectory:(NSSearchPathDirectory)searchPathDirectory searchPathDomainMask:(NSSearchPathDomainMask)searchPathDomainMask
{
    MLURL *url = (MLURL *)[MLURL fileURLWithPath:path isDirectory:isDir];
    if (url) {
        url.searchPathDirectory = searchPathDirectory;
        url.searchPathDomainMask = searchPathDomainMask;
        url.isForSearchPath = YES;
    }
    return url;
}

- (NSString*)path
{
    NSString *path = [super path];
    if ([self isFileURL]&&self.isForSearchPath) {
        //添加路径前缀
        NSString *searchDitPath = [NSSearchPathForDirectoriesInDomains(self.searchPathDirectory, self.searchPathDomainMask, YES) firstObject];
        path = [searchDitPath stringByAppendingPathComponent:path];
    }
    return path;
}


- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        self.isForSearchPath = [[coder decodeObjectForKey:SELSTR(isForSearchPath)]boolValue];
        self.searchPathDomainMask = [[coder decodeObjectForKey:SELSTR(searchPathDomainMask)]integerValue];
        self.searchPathDirectory = [[coder decodeObjectForKey:SELSTR(searchPathDirectory)]integerValue];
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder {
    [super encodeWithCoder:aCoder];
    [aCoder encodeObject:@(self.isForSearchPath) forKey:SELSTR(isForSearchPath)];
    [aCoder encodeObject:@(self.searchPathDomainMask) forKey:SELSTR(searchPathDomainMask)];
    [aCoder encodeObject:@(self.searchPathDirectory) forKey:SELSTR(searchPathDirectory)];
}

//TODO:最好也得实现copy


- (NSURL*)commonURL
{
    if ([self isFileURL]&&self.isForSearchPath) {
        return [NSURL fileURLWithPath:[self path]];
    }
    return self;
}

@end
